class AppVersionPanel {
    constructor(homeApp) {
        this.app = homeApp;
        this.modal = null;
        this.currentVersionTemplate = null;
    }

    initAppVersionPanel() {
        // 初始化上传新版本按钮
        const uploadAppVersionBtn = document.getElementById('upload-app-version-btn');
        if (uploadAppVersionBtn) {
            uploadAppVersionBtn.addEventListener('click', () => {
                this.showUploadAppVersionModal();
            });
        }
        
        // 加载当前App版本信息
        this.loadCurrentAppVersion();
    }

    async loadCurrentAppVersion() {
        try {
            const response = await this.app.authenticatedFetch('/api/web/app/version/latest');
            const result = await response.json();
            
            if (result.code === 200) {
                const version = result.data || null;
                this.renderCurrentVersion(version);
            } else {
                console.error('获取当前App版本信息失败:', result.message);
                this.renderCurrentVersion(null);
            }
        } catch (error) {
            console.error('加载当前App版本信息失败:', error);
            this.renderCurrentVersion(null);
        }
    }

    async loadCurrentVersionTemplate() {
        try {
            // 加载外部模板
            const response = await fetch('/templates/current-version-template.html');
            const template = await response.text();
            this.currentVersionTemplate = template;
            return template;
        } catch (error) {
            console.error('加载当前版本信息模板失败:', error);
            return null;
        }
    }

    async renderCurrentVersion(version) {
        const container = document.getElementById('current-version-info');
        if (!container) return;

        // 如果模板尚未加载，则先加载模板
        if (!this.currentVersionTemplate) {
            await this.loadCurrentVersionTemplate();
        }

        if (!version) {
            container.innerHTML = '<p>暂无版本信息</p>';
            return;
        }

        // 使用外部模板
        container.innerHTML = this.currentVersionTemplate;

        // 填充数据
        const versionCodeElement = container.querySelector('#version-code');
        if (versionCodeElement) {
            versionCodeElement.textContent = version.versionCode || '-';
        }

        const versionNameElement = container.querySelector('#version-name');
        if (versionNameElement) {
            versionNameElement.textContent = version.versionName || '-';
        }

        const fileSizeElement = container.querySelector('#file-size');
        if (fileSizeElement) {
            fileSizeElement.textContent = version.fileSize ? (version.fileSize / 1024 / 1024).toFixed(2) + ' MB' : 'N/A';
        }

        const descriptionElement = container.querySelector('#version-description');
        if (descriptionElement) {
            descriptionElement.textContent = version.description || '无';
        }

        const createDateElement = container.querySelector('#create-date');
        if (createDateElement) {
            createDateElement.textContent = version.createDate ? new Date(version.createDate).toLocaleString() : '-';
        }

        const updateDateElement = container.querySelector('#update-date');
        if (updateDateElement) {
            updateDateElement.textContent = version.updateDate ? new Date(version.updateDate).toLocaleString() : '-';
        }

        const downloadLinkElement = container.querySelector('#download-link');
        if (downloadLinkElement && version.filePath) {
            downloadLinkElement.href = version.filePath;
        }
    }

    async initAppVersionModal() {
        try {
            // 加载外部模态框模板
            const response = await fetch('/templates/app-version-modal.html');
            const template = await response.text();
            
            // 创建模态框
            if (!this.modal) {
                this.modal = document.createElement('div');
                this.modal.className = 'modal';
                this.modal.id = 'app-version-modal';
                document.body.appendChild(this.modal);
            }
            
            this.modal.innerHTML = template;
            return this.modal;
        } catch (error) {
            console.error('加载App版本模态框模板失败:', error);
            return null;
        }
    }

    showUploadAppVersionModal() {
        // 初始化模态框
        this.initAppVersionModal().then(modal => {
            if (!modal) {
                console.error('无法加载App版本模态框模板');
                alert('无法打开App版本模态框，请稍后重试');
                return;
            }

            // 获取表单元素
            const form = modal.querySelector('#upload-app-version-form');
            const closeBtn = modal.querySelector('.close');
            const cancelBtn = modal.querySelector('#cancel-app-version');

            // 移除之前可能存在的事件监听器
            if (this.currentCloseHandler) {
                closeBtn.removeEventListener('click', this.currentCloseHandler);
            }
            if (this.currentCancelHandler) {
                cancelBtn.removeEventListener('click', this.currentCancelHandler);
            }
            if (this.currentFormSubmitHandler) {
                form.removeEventListener('submit', this.currentFormSubmitHandler);
            }

            const closeModal = () => {
                modal.style.display = 'none';
            };

            // 绑定关闭事件
            if (closeBtn) {
                this.currentCloseHandler = closeModal;
                closeBtn.addEventListener('click', closeModal);
            }

            if (cancelBtn) {
                this.currentCancelHandler = closeModal;
                cancelBtn.addEventListener('click', closeModal);
            }

            // 表单提交事件
            if (form) {
                this.currentFormSubmitHandler = (e) => this.handleUploadAppVersionSubmit(e);
                form.addEventListener('submit', this.currentFormSubmitHandler);
            }

            // 显示模态框
            modal.style.display = 'block';
        });
    }

    async handleUploadAppVersionSubmit(e) {
        e.preventDefault();
        
        const versionCode = document.getElementById('versionCode').value;
        const versionName = document.getElementById('versionName').value;
        const description = document.getElementById('description').value;
        const fileInput = document.getElementById('file');
        
        // 检查文件是否已选择
        if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
            alert('请选择要上传的APK文件');
            return;
        }
        
        const file = fileInput.files[0];

        const formData = new FormData();
        formData.append('versionCode', versionCode);
        formData.append('versionName', versionName);
        formData.append('description', description);
        formData.append('file', file);

        try {
            const response = await this.app.authenticatedFetch('/api/web/app/upload', {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误: ' + resultText);
            }

            if (result.code === 200) {
                alert('App版本上传成功');
                // 关闭模态框
                if (this.modal) {
                    this.modal.style.display = 'none';
                }
                // 重新加载当前版本信息
                this.loadCurrentAppVersion();
            } else {
                alert('上传失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('上传App版本失败:', error);
            alert('上传App版本失败，请稍后重试: ' + error.message);
        }
    }
}